package com.comm9;

public class ConsumerProducerTest {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        Producer p1 = new Producer(clerk);
        Consumer c1 = new Consumer(clerk);
        Consumer c2 = new Consumer(clerk);
        p1.setName("生产者1");
        c1.setName("消费者1");
        c2.setName("消费者2");
        p1.start();
        c1.start();
        c2.start();
    }
}
//生产线程类
class Producer extends Thread{

    private Clerk clerk;
    public Producer(Clerk clerk){
        this.clerk = clerk;
    }
    @Override
    public void run() {
        System.out.println("生产者开始生产产品");
        while (true){
            try {
                Thread.sleep(40);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
//            要求clerk去增加产品
            clerk.addProduct();
        }
    }
}
// 消费者线程
class Consumer extends Thread{
    private Clerk clerk;
    public Consumer(Clerk clerk){
        this.clerk = clerk;
    }

    @Override
    public void run() {
        while (true){
            try {
                Thread.sleep(90);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
//            要求clerk去增加产品
            clerk.minusProduct();
        }
    }
}

class Clerk {
    //    产品数量
    private int productNum = 0;
    //    最多产品数量为20
    private static final int MAX_PRODUCT = 20;
    //    最少产品数量为1
    private static final int MIN_PRODUCT = 1;

    //    增加产品
    public synchronized void addProduct() {
        if (productNum < MAX_PRODUCT) {
            productNum++;
            System.out.println(Thread.currentThread().getName()
                    + "生产了第" + productNum + "个产品");
//        唤醒消费者
            this.notifyAll();
        }else {
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

    }

    public synchronized void minusProduct(){
        if (productNum >= MIN_PRODUCT) {
            productNum--;
            System.out.println(Thread.currentThread().getName()
                    + "生产了第" + productNum + "个产品");
//        唤醒生产
            this.notifyAll();
        }else {
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
